package com.linzm.leetcode.mid.tree.层次遍历;

import java.util.*;

/**
 * @Author zimingl
 * @Date 2023/2/19 14:39
 * @Description: 二叉树的层序遍历
 */
public class LevelOrder102 {
    public static void main(String[] args) {
        LevelOrder102 levelOrder102 = new LevelOrder102();
        List<List<Integer>> lists = levelOrder102.levelOrder(TreeNode.getTree());
        System.out.println(lists);
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> resList = new ArrayList<>();
        dfs(root, 0, resList);
//        bfs(root, resList);
        return resList;
    }

    //DFS--递归方式
    public void dfs(TreeNode treeNode, Integer deep, List<List<Integer>> resList) {
        if (treeNode == null) return;
        deep++;
        if (resList.size() < deep) {
            //当层级增加时，list的Item也增加，利用list的索引值进行层级界定
            List<Integer> item = new ArrayList<>();
            resList.add(item);
        }
        resList.get(deep - 1).add(treeNode.val);
        dfs(treeNode.left, deep, resList);
        dfs(treeNode.right, deep, resList);
    }

    //BFS--迭代方式--借助队列
    public void bfs(TreeNode treeNode, List<List<Integer>> resList) {
        if (treeNode == null) return;
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(treeNode);
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int len = queue.size();
            while (len > 0) {
                TreeNode tmpTreeNode = queue.poll();
                list.add(tmpTreeNode.val);
                if (tmpTreeNode.left != null) queue.offer(tmpTreeNode.left);
                if (tmpTreeNode.right != null) queue.offer(tmpTreeNode.right);
                len--;
            }
            resList.add(list);
        }
    }
}
